﻿using CodeNotes.BLL;
using CodeNotes.Common;
using CodeNotes.Model;
using Maticsoft.Common;
using MvcCodeNotes.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace MvcCodeNotes.Controllers
{
    public class BookController : BaseController
    {
        //
        // GET: /Book/

        public ActionResult Index()
        {


            return View();
        }

        public ActionResult ChapterList(int? bid)
        {
            if (bid == null || bid <= 0)
                return RedirectToAction("Index");
            CW_Book book = new CW_BookLogic().GetModel(Convert.ToInt32(bid));
            List<CW_BookChapter> chapters = new List<CW_BookChapter>();
            if (book == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                string strFields = " Id,BookId,ChapterName,ClickCount,CreateDate,Sort";
                string strWhere = "BookId=" + bid + " order by Sort,Id";
                chapters = new CW_BookChapterLogic().GetFixedColumnModelList(strFields, strWhere);
            }

            new CW_BookLogic().addClickCount(Convert.ToInt32(bid));

            ViewBag.chapters = chapters;
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            string arrList = ser.Serialize(chapters).ToString();
            ViewBag.jaonChapter = arrList;
            return View(book);
        }

        public ActionResult Chapter(int? bid, int? cid)
        {
            if (cid == null || cid <= 0)
                return RedirectToAction("ChapterList", new { bid = bid });
            CW_BookChapter chapter = new CW_BookChapterLogic().GetModel(Convert.ToInt32(cid));
            if (chapter == null)
            {
                return RedirectToAction("ChapterList", new { bid = bid });
            }
            //下一章节的id
            ViewBag.nextid = getNextChapterid(chapter.BookId, chapter.Id);
            ViewBag.book = new CW_BookLogic().GetModel(chapter.BookId);

            new CW_BookChapterLogic().addClickCount(Convert.ToInt32(cid));

            return View(chapter);
        }

        [HttpPost]
        public JsonResult GetChapter(string callback, int bid, int cid)
        {
            CW_BookChapter chapter = new CW_BookChapterLogic().GetModel(cid);
            int nextid = 0;
            if (chapter != null)
            {
                //下一章节的id
                nextid = getNextChapterid(chapter.BookId, chapter.Id);
            }
            var obj = new
            {
                chapter = chapter,
                nextid = nextid
            };
            new CW_BookChapterLogic().addClickCount(Convert.ToInt32(cid));
            return Json(obj);
        }

        public int getNextChapterid(int bid, int cid)
        {
            int nextid = 0;
            string strFields = " Id,ChapterName,Sort";
            string strWhere = "BookId=" + bid + " order by Sort,Id";
            List<CW_BookChapter> chapters = new CW_BookChapterLogic().GetFixedColumnModelList(strFields, strWhere);
            int idx = chapters.FindIndex(p => p.Id == cid);
            if (chapters.Count > idx + 1)
            {
                nextid = chapters[idx + 1].Id;
            }

            return nextid;
        }

        //小说目录
        public void getChapterList()
        {
            //http://www.8dushu.com/xiaoshuo/64/64994/   养鬼为夫
            //http://book.zongheng.com/showchapter/373142.html
            //棉花糖网站
            string url = "http://www.mianhuatang.la/0/707/";
            string bookname = "兽武乾坤";
            string EncodingStr = "GBK";

            bool isError = false;
            string errorMsg = "";
            try
            {
                CW_Book book = new CW_Book();
                book.BookName = bookname;
                book.ClickCount = 0;
                book.IsOver = false;
                book.Source = url;
                book.CreateDate = DateTime.Now;
                book.UpdateDate = DateTime.Now;
                book.Sort = 0;
                book.IsShow = true;
                int bookid = new CW_BookLogic().Add(book);


                string html = BookFetch.GetHtml(url, EncodingStr);
                Regex regReplace = new Regex("<script[\\s\\S]*?>[\\s\\S]*?</script>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                html = regReplace.Replace(html, "");

                //去掉最新章节部分
                int idx = html.IndexOf("class=\"novel_list\"");
                if (idx > -1)
                {
                    html = html.Substring(idx);
                }
                if (string.IsNullOrEmpty(html) || bookid <= 0)
                {
                    isError = true;
                    errorMsg = "小说目录页面，此页面抓取为空;bookid=" + bookid;
                }
                else
                {
                    string pattern = "<dd><a\\s+href=\"(?<id>\\d+).html\">(?<title>[\\s\\S]*?)</a></dd>";
                    MatchCollection mContent = Regex.Matches(html, pattern, RegexOptions.IgnoreCase);
                    if (mContent.Count > 0)
                    {
                        for (int i = 0; i < mContent.Count; i++)
                        {
                            string id = mContent[i].Groups["id"].Value.Trim();
                            string title = mContent[i].Groups["title"].Value.Trim();

                            if (id != "")
                            {
                                string urlDetail = url + id + ".html";
                                //判断这个章节有没有被抓取过
                                int existCount = new CW_BookChapterLogic().GetRecordCount("Source='" + urlDetail + "' and BookId=" + bookid);
                                //int existCount =0;
                                if (existCount == 0)
                                    getChapter(id, title, urlDetail, bookname, bookid, EncodingStr);
                            }
                        }
                    }
                    else
                    {
                        isError = true;
                        errorMsg = "小说目录页面--抓取章节地址，【正则表达式匹配为0条数据】";
                    }
                }
            }
            catch (Exception ex)
            {
                isError = true;
                errorMsg = ex.Message.ToString();
            }
            if (isError)
            {
                CW_BookFetchLog log = new CW_BookFetchLog();
                log.BookName = bookname;
                log.FetchUrl = url;
                log.ErrorMsg = errorMsg;
                log.CreateDate = DateTime.Now;
                new CW_BookFetchLogLogic().Add(log);
            }


        }


        //单章小说
        public void getChapter(string id, string chapterTitle, string url, string bookname, int bookid, string EncodingStr)
        {
            try
            {
                string html = BookFetch.GetHtml(url, EncodingStr);
                Regex regReplace = new Regex("<script[\\s\\S]*?>[\\s\\S]*?</script>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                html = regReplace.Replace(html, "").Replace(" 一秒记住【棉花糖小说网www.mianhuatang.la】，为您提供精彩小说阅读。", "");

                ////去掉小说内容中的a标签,正则表达式错误
                //Regex aReplace = new Regex("<a[\\s\\S]*>[\\s\\S]*</a>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                //html = aReplace.Replace(html, "");

                string patternContent = "<div\\s+class=\"content\"\\s+id=\"con" + id + "\">\\s*(?<content>[\\s\\S]*?)<div\\s+class=\"con_l\">";
                string m_content = "";
                Regex reg2 = new Regex(patternContent, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                Match mc2 = reg2.Match(html);
                if (mc2.Success)
                    m_content = mc2.Groups["content"].Value.Trim();

                //如果保存成txt格式，得去掉html标签
                //string content = m_content.Replace("<br>", "\r\n").Replace("<br/>", "\r\n").Replace("<br />", "\r\n").Replace("&nbsp;", " ");
                string content = m_content;
                string retTitle = BookFetch.ParseTags(chapterTitle);
                string retContent = content;

                if (!string.IsNullOrEmpty(retTitle) && !string.IsNullOrEmpty(retContent))
                {
                    CW_BookChapter chapter = new CW_BookChapter()
                    {
                        BookId = bookid,
                        ChapterName = retTitle,
                        ChapterContent = retContent,
                        ClickCount = 0,
                        Source = url,
                        CreateDate = DateTime.Now,
                        Sort = 0
                    };
                    new CW_BookChapterLogic().Add(chapter);
                }

            }
            catch (Exception ex)
            {
                CW_BookFetchLog log = new CW_BookFetchLog();
                log.BookName = bookname + "——" + chapterTitle;
                log.FetchUrl = url;
                log.ErrorMsg = ex.Message.ToString();
                log.CreateDate = DateTime.Now;
                new CW_BookFetchLogLogic().Add(log);
            }

        }


        //小说分类
        public ActionResult Category(int? typeid, int? idx)
        {
            if (typeid == null || typeid <= 0)
                return RedirectToAction("Index");

            if (idx == null || idx < 1)
                idx = 1;

            string typeName = Enum.GetName(typeof(EnumBookCategory), typeid);
            ViewBag.typeName = typeName;
            ViewBag.idx = idx;
            ViewBag.typeid = typeid;
            return View();
        }

        [HttpPost]
        public JsonResult BooksByCategory(int? typeid, int? idx)
        {

            string strWhere = "IsShow=1 ";
            if (typeid != null || typeid > 0)
            {
                strWhere += " and Category=" + typeid;
            }
            if (idx == null || idx < 1)
                idx = 1;
            int index = idx <= 1 ? 1 : Convert.ToInt32(idx);
            SP_Pagination sp = new SP_Pagination
            {
                TableName = "CW_Book",
                Fields = "*",
                OrderField = "Sort",
                PageSize = 20,
                PageIndex = index,
                SortAsc = false,
                strWhere = strWhere
            };
            DataTable dt = sp.GetList().Tables[0];
            List<object> books = new List<object>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {

                string IsOver = dt.Rows[i]["IsOver"].ToString() == "True" ? "已完结" : "连载中";
                int CategoryId = Convert.ToInt32(dt.Rows[i]["Category"].ToString());

                string typeName = Enum.GetName(typeof(EnumBookCategory), CategoryId);
                var book = new
                {
                    id = dt.Rows[i]["Id"].ToString(),
                    bookname = dt.Rows[i]["BookName"].ToString(),
                    author = dt.Rows[i]["Author"].ToString(),
                    desc = dt.Rows[i]["Descriotion"].ToString(),
                    updateDate = Convert.ToDateTime(dt.Rows[i]["UpdateDate"]).ToString("yyyy-MM-dd"),
                    typeName = typeName,
                    isOver = IsOver
                };
                books.Add(book);
            }

            var obj = new
            {
                state = "success",
                books = books
            };
            return Json(books);
        }

        [HttpPost]
        public JsonResult HomePageData()
        {
            List<object> Data = new List<object>();
            DataTable dt = BookCommon.GetHomepagedataByCache();
            foreach (int sortid in Enum.GetValues(typeof(EnumBookCategory)))
            {
                string typeName = Enum.GetName(typeof(EnumBookCategory), sortid);
                DataRow[] drs = dt.Select("Category= " + sortid);
                List<object> categoryList = new List<object>();

                foreach(var dr in drs)
                {
                    var book = new
                    {
                        Id = dr["Id"].ToString(),
                        BookName = dr["BookName"].ToString(),
                        Author = dr["Author"].ToString()
                    };
                    categoryList.Add(book);
                }
                var booklist = new
                {
                    typeName = typeName,
                    typeid = sortid,
                    list = categoryList
                };
                Data.Add(booklist);
            }

            return Json(Data);
        }

        public ActionResult Search(int? page, string keyword)
        {
            ViewBag.Searchword = keyword;
            return View();

        }
        [HttpPost]
        public JsonResult SearchData(int? page, string keyword)
        {
            List<object> books = new List<object>();
            if (!string.IsNullOrEmpty(keyword))
            {
                int pageSize = 15;
                int pageIndex = page == null ? 0 : Convert.ToInt32(page);

                List<CW_Book> listTemp = new CW_BookLogic().GetModelListByKeyword(keyword);

                for (int i = pageIndex * pageSize; i < listTemp.Count && i < (pageIndex + 1) * pageSize; i++)
                {
                    CW_Book bk = listTemp[i];
                    string IsOver = bk.IsOver ? "已完结" : "连载中";
                    string typeName = "";
                    if (bk.Category > 0)
                    {
                        typeName = Enum.GetName(typeof(EnumBookCategory), bk.Category);
                    }

                    string desc = bk.Descriotion.Replace(keyword, "<span class='cTheme'>" + keyword + "</span>");

                    var book = new
                    {
                        id = bk.Id,
                        bookname = bk.BookName,
                        author = bk.Author,
                        desc = desc,
                        updateDate = Convert.ToDateTime(bk.UpdateDate).ToString("yyyy-MM-dd"),
                        typeName = typeName,
                        isOver = IsOver
                    };
                    books.Add(book);
                }
            }

            return Json(books);
        }

    }
}
